#!/bin/bash
#第一个参数为：start|restart|stop|reload|list
#第二个参数为应用名，如：mybbs
#如不传入第二个参数，则操作所有应用
#list 参数，列出当前所有运行中的应用
path=$(cd `dirname "$0"`;pwd)
script_name="$0";
php=/usr/local/php/bin/php
cmd="$1"
fail='[\033[1;31mfail\033[0m]'
ok='[\033[1;32mOK\033[0m]'
if [ -z "${cmd}" ];then
  echo "Usega:$script_name start|stop|restart|reload|list"
  exit 0
fi
#if [ "$1" != "list" -a -z "$2" ];then
  #echo -e "Please type the appServer name. ie:59pi    $fail"
  #exit 1
#fi
do_start(){
  app_name="$1"
  pid_file=$path/logs/$app_name.pid
  if [ -e "$pid_file" ];then
    echo -e "The appServer $app_name is runing    $fail"
  else
    out=`php $path/appServer.php $app_name`
    if [ ! -z "$out" ];then
      echo -e "$out    $fail"
    fi
    echo -e "Starting $app_name \c"
    while [ ! -e "$pid_file" ];do
      echo -e '.\c'
      sleep 0.1
    done
    echo -e "    $ok"
  fi
}

do_stop(){
  app_name="$1"
  pid_file=$path/logs/$app_name.pid
  if [ ! -e $pid_file ];then
    echo -e "The appServer $app_name no runing    $fail"
  else
    pid=`cat "$pid_file"`
    ret=$(kill -15 "$pid")
    echo -e "Stoping $app_name \c"
    while [ -e "$pid_file" ];do
      echo -e '.\c'
      sleep 0.1
    done
    echo -e "    $ok"
  fi
}

do_reload(){
  app_name="$1"
  pid_file=$path/logs/$app_name.pid
  if [ ! -e "$pid_file" ];then
    echo -e "The appServer $app_name no runing    $fail";
  fi
   ps aux|grep "php-master $app_name"|grep -v grep|awk '{print $2}'|xargs kill -USR1
   echo -e "Reload appServer $app_name    $ok"
}

do_list(){
  ps aux|grep php|grep -v fpm|grep -v grep|awk '{print $2 "\t" $11 " " $12}'
  exit 0
}

etc_path=$path/etc

case "$1" in
  start)
    if [ ! -z "$2"  ];then
      do_start $2
    else
      for app in $(ls "$etc_path"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        do_start $app
      done
    fi;;

  stop)
    if [ ! -z "$2" ];then
      do_stop $2
    else
      for app in $(ls "$etc_path"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        do_stop $app
      done
    fi;;


  restart)
    if [ ! -z "$2" ];then
      do_stop $2
    else
      for app in $(ls "$etc_path"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        do_stop $app
      done
    fi
    if [ ! -z "$2" ];then
      do_start $2
    else
      for app in $(ls "$etc_path"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        do_start $app
      done
    fi;;


  reload)
    if [ ! -z "$2" ];then
      do_reload $2
    else
      for app in $(ls "$etc_path"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        do_reload $app
      done
    fi;;

  list)
    do_list;;
  *)
    echo "Usega:$script_name start|stop|restart|reload|list"
    exit 1;;
esac
exit 0
